/**
 *  This file is part of AugeasWH.
 *
 *  AugeasWH. is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AugeasWH. is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AugeasWH.  If not, see <http://www.gnu.org/licenses/>.
 */

package cz.fit.vutbr.pis2012.augeaswh.control.administration.user;

import java.io.Serializable;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import cz.fit.vutbr.pis2012.augeaswh.managers.UserManager;
import cz.fit.vutbr.pis2012.augeaswh.persistence.User;
import cz.fit.vutbr.pis2012.augeaswh.utils.FacesUtils;;

@ManagedBean
@SessionScoped
public class UsersEditorBean implements Serializable {
	
	@EJB
	private UserManager userManager;
	
	private static final long serialVersionUID = -9017211337466643565L;
	private User editedUser;
	private String userName;
	private String userPassword;
	private String userRole;
	
	public User getEditedUser() {
		return editedUser;
	}
	
	public void setEditedUser(User editedUser) {
		if (editedUser == null)
			editedUser = new User();
		this.editedUser = editedUser;
		userName = editedUser.getName();
		userPassword = editedUser.getPassword();
		userRole = editedUser.getRole();
	}
	
	public String getUserName() {
		return userName;
	}
	
	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	public String getUserPassword() {
		return userPassword;
	}
	
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	
	public String getUserRole() {
		return userRole;
	}
	
	public void setUserRole(String userRole) {
		this.userRole = userRole;
	}
	
	public String save() {
		if (editedUser != null) {
			editedUser.setName(userName);
			editedUser.setPassword(userPassword);
			editedUser.setRole(userRole);
			try {
				userManager.saveOrUpdateUser(editedUser);
			} catch (Exception e) {
				FacesUtils.addFacesMessage("", e.getMessage());
			}
		}
		editedUser = null;
		return "user_list";
	}
	
	public String cancel() {
		editedUser = null;
		return "user_list";
	}
	
	public String getTitle() {
		if (editedUser.getId() == null) 
			return "Fill the form to add new user";
		return "Fill the form to edit \"" + editedUser.getName() + "\"";
	}
}
